<template>
  <div style="height: 350px; overflow: auto;">
    <el-form ref="editForm" :model="addFormItem" label-width="100px" size="mini" style="width: 95%;" class="form-view">
      <input v-model="addFormItem._id" type="hidden">
      <el-row :gutter="10" type="flex" align="middle" style="margin-bottom: 5px;">
        <el-col :span="4" style="">
          <div style="text-align: right;">属性</div>
        </el-col>
        <el-col :span="8">
          变更前
        </el-col>
        <el-col :span="12">
          变更后
        </el-col>
      </el-row>
      <el-row :gutter="10" type="flex" align="middle">
        <el-col :span="12">
          <el-form-item label="描述" required>
            {{ addFormItem.desc }}
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label-width="0">
            {{ addFormItem.descChange }}
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10" type="flex" align="middle">
        <el-col :span="12">
          <el-form-item label="关联关系">
            {{ addFormItem.relaDesc }}
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label-width="0">
            {{ addFormItem.relaDesc }}
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10" type="flex" align="middle">
        <el-col :span="12">
          <el-form-item label="源实例">
            {{ addFormItem.srcDesc }}
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label-width="0">
            {{ addFormItem.srcDesc }}
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10" type="flex" align="middle">
        <el-col :span="12">
          <el-form-item label="目标实例">
            {{ addFormItem.destDesc }}
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label-width="0">
            {{ addFormItem.destDesc }}
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-for="(attr, index) in addFormItem.attrs" :key="attr.field" :gutter="10" type="flex" align="middle">
        <el-col :span="12">
          <el-form-item :label="attr.name">
            <span v-if="attr.dtype!=='bool'">{{ attr.val }}</span>
            <bool-checkbox v-else-if="attr.dtype==='bool'" v-model="attr.val" :disabled="true" />

            <!-- <number-input v-if="attr.dtype==='number'" v-model="addFormItem.attrs[index].val" :disabled="true" />
            <bool-checkbox v-else-if="attr.dtype==='bool'" v-model="addFormItem.attrs[index].val" :disabled="true" />
            <date-input v-else-if="attr.dtype==='date'" v-model="addFormItem.attrs[index].val" :disabled="true" />
            <string-input v-else v-model="addFormItem.attrs[index].val" :maxlen="addFormItem.attrs[index].len" :disabled="true" /> -->
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label-width="0">
            <span v-if="attr.dtype!=='bool'">{{ addFormItem.attrsChange[index].val }}</span>
            <bool-checkbox v-else-if="attr.dtype==='bool'" v-model="addFormItem.attrs[index].val" :disabled="true" />

            <!-- <number-input v-if="attr.dtype==='number'" v-model="addFormItem.attrsChange[index].val" />
            <bool-checkbox v-else-if="attr.dtype==='bool'" v-model="addFormItem.attrsChange[index].val" />
            <date-input v-else-if="attr.dtype==='date'" v-model="addFormItem.attrsChange[index].val" />
            <string-input v-else v-model="addFormItem.attrsChange[index].val" :maxlen="addFormItem.attrsChange[index].len" /> -->
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import databind from '@neu/biz-core/mixins/databind'
import { detail as instanceDetail, getRelations, listBySchema, removeRelation } from '@neu/dcom-ui/api/instance'
import { getRelations as getSchemaRelatins } from '@neu/dcom-ui/api/schema'

const addFormItem = {
  desc: '',
  src: '',
  srcDesc: '',
  dest: '',
  destDesc: '',
  rela: '',
  relaDesc: '',
  attrs: [],
  descChange: '',
  attrsChange: [],
  relationId: ''
}

function deepCopyObj(obj) {
  if (typeof obj !== 'object') {
    return obj
  }
  var newobj = {}
  for (var attr in obj) {
    newobj[attr] = deepCopyObj(obj[attr])
  }
  return newobj
}

export default {
  name: 'ExistEditFormView',
  components: {
  },
  mixins: [databind],
  props: {
    // 根据id可判断是新建还是更新
    id: {
      required: false,
      type: Number,
      default: -1
    },
    instanceId: {
      required: true,
      type: String
    },
    row: {
      required: false,
      type: Object,
      default: function() {
        return {}
      }
    }
  },
  data() {
    return {
      instance: {},
      // 可用的关系（与模型定义有关）
      availableRelations: [],
      // 可选的目标实例（与关联关系的目标模型设置有关）
      availableSrcInstances: [],
      availableDestInstances: [],
      addRelaDialogVisible: false,
      r: getRelations(this.instanceId),
      d: removeRelation(this.instanceId),
      addFormItem: {
        ...addFormItem
      }
    }
  },
  watch: {
    // 监控id的变化，初始化表单数据
    id: {
      handler(newVal, oldVal) {
        this.fetch()
      },
      immediate: true
    }
  },
  created() {},
  methods: {
    // 初始化表单数据
    fetch() {
      if (this.id !== -1) {
        this.addFormItem = deepCopyObj(this.row)
        instanceDetail(this.instanceId).then(response => {
          this.instance = response.data
          getSchemaRelatins(this.instance.schemadef._id)().then(response1 => {
            this.availableRelations = response1.data
            this.onRelationChange(this.addFormItem.rela)
          })
        })
      } else {
        this.addFormItem = deepCopyObj(addFormItem)
        instanceDetail(this.instanceId).then(response => {
          this.instance = response.data
          getSchemaRelatins(this.instance.schemadef._id)().then(response1 => {
            this.availableRelations = response1.data
          })
        })
      }
    },
    save() {
      const { desc, src, dest, rela, attrs, srcDesc, destDesc, relaDesc, descChange, attrsChange, relationId, index } = this.addFormItem
      const data = { desc, src, dest, rela, attrs: {}, srcDesc, destDesc, relaDesc, descChange, attrsChange: {}, relationId, index }
      attrs.forEach(a => {
        data.attrs[a.field] = a.val
      })
      attrsChange.forEach(a => {
        data.attrsChange[a.field] = a.val
      })
      data.addFlag = false
      data.deleteFlag = false

      const updated = this.id !== -1
      return new Promise(resolve => {
        this.$refs.editForm.validate((valid) => {
          if (valid) {
            if (updated) {
              resolve(this.$emit('existEditRow', data))
              // resolve(update(this.id, data))
            } else {
              // resolve(create(data))
            }
          } else {
            // resolve(false)
          }
        })
      })
    },
    onRelationChange(relationId) {
      const relation = this.availableRelations.find(it => it._id === relationId)
      this.addFormItem.relaDesc = relation.desc
      const srcSchemaId = relation.src._id
      if (this.instance.schemadef._id === srcSchemaId) {
        this.availableSrcInstances = [this.instance]
        this.addFormItem.srcDesc = this.instance.name
        this.addFormItem.src = this.instanceId
        listBySchema(relation.dest._id).then(response => {
          this.availableDestInstances = response.data
        })
      } else {
        this.availableDestInstances = [this.instance]
        this.addFormItem.dest = this.instanceId
        listBySchema(relation.src._id).then(response => {
          this.availableSrcInstances = response.data
        })
      }

      var attrs = relation.attrs.map(it => {
        let value = ''
        for (const key in this.addFormItem.attrs) {
          if (it.field === key) {
            value = this.addFormItem.attrs[key]
          }
        }
        return {
          field: it.field,
          name: it.name,
          val: value,
          dtype: it.dtype,
          notnullable: it.notnullable,
          len: it.len
        }
      })
      this.addFormItem.attrs = attrs

      var attrsChange = relation.attrs.map(it => {
        let value = ''
        for (const key in this.addFormItem.attrsChange) {
          if (it.field === key) {
            value = this.addFormItem.attrsChange[key]
          }
        }
        return {
          field: it.field,
          name: it.name,
          val: value,
          dtype: it.dtype,
          notnullable: it.notnullable,
          len: it.len
        }
      })
      this.addFormItem.attrsChange = attrsChange
    },
    onSrcChange(val) {
      const obj = this.availableSrcInstances.find((item) => {
        return item._id === val
      })
      this.addFormItem.srcDesc = obj.name
    },
    onDestChange(val) {
      const obj = this.availableDestInstances.find((item) => {
        return item._id === val
      })
      this.addFormItem.destDesc = obj.name
    },
    reset() {
      this.$refs.editForm.resetFields()
      this.addFormItem = deepCopyObj(addFormItem)
    }
  }
}
</script>
